<?php

/** 
 * 数据表搜索模板
 * 
 */
class Search_tpl {
	
	private $ci = NULL;
	private $db = NULL;
	private $list = array();
	private $rowCount  = 0;
	private $page  = 1;
	private $pagesize = 20;
	public $debug = FALSE;
	private $tplPath = 'admin/search_tpl';
	
	public function __construct() {
		$this->ci = &get_instance();
		$this->ci->load->database('comment'); 
		$this->db = &$this->ci->db;
		if ( isset($_REQUEST['page']) ) {
			$page = (int)$_REQUEST['page'];
			$this->page = $page > 1 ? $page : 1;
		}
		if( isset($_REQUEST['pagesize']) ){
			$pagesize = (int)$_REQUEST['pagesize'];
			$this->pagesize = $pagesize > 1 ? $pagesize : 20;
		}
		$this->debug = ENVIRONMENT==='development' || ( defined('IS_TEST') && IS_TEST );
	}
	
	public function query($query){
		$select = '*';
		if( isset($query['select']) ){
			$select = $query['select'];
			unset($query['select']);
		}
		if( isset($query['from']) ){
			$table = $query['from'];
			unset($query['from']);
		}else{
			trigger_error('未输入表名',E_USER_ERROR);
			exit();
		}
		foreach($query as $k=>$v){
			if( empty($v) ){
				continue;
			}
			switch ($k){
				case 'where':
// 					var_dump($v);die;
					foreach ($v as $kk=>$vv){
						if(is_numeric($kk)){
							$this->db->where($vv);
						}else{
							$this->db->where($kk,$vv);
						}
					}
// 					var_dump($v);die;
// 					$this->db->where($v);
					break;
				case 'where_in':
					$this->db->where_in($v['field'],$v['list']);
					break;
				case 'like':
					$this->db->like($v);
					break;
				case 'order' :
					$sort = (isset($query['sort']) && strtoupper($query['sort'])==='DESC') ? 'DESC' : 'ASC';  
					$order = $table.'.'.$v;
					$this->db->order_by($order,$sort);
					break;
				case 'join':
					$joins = array();
					$joinSelect = '';
					// 如果是关联数组(即只JOIN一个表),转为索引数组
					if( array_keys($v)!== range(0,count($v)-1) ){
						$joins[] = $v;
					}else{
						$joins = $v;
					}
					foreach ($joins as $join){
						$joinTable = $join['table'];
						if( isset($join['select']) ){
							$_joinSelect= str_replace(',', ','.$joinTable.'.', $join['select']);
							$joinSelect.=$joinTable.'.'.$_joinSelect.',';
						}
						if( is_array($join['on']) ){
							$joinOn = $table.'.'.$join['on']['fk'].'='.$joinTable.'.'.$join['on']['pk'];
						}else{
							$joinOn = $join['on'];
						}
						$joinType = isset($join['type']) ? $join['type'] : '';
						$this->db->join($joinTable,$joinOn,$joinType);
					}
					break;
				case 'group':
					$this->db->group_by($v);
					break;
			}
		}
		
		if( !empty($joinSelect) ){
			$joinSelect = rtrim($joinSelect,',');
			$select = str_replace(',', ','.$table.'.', $select);
			$select = $table.'.'.$select.','.$joinSelect;
		}
		
		$select = 'SQL_CALC_FOUND_ROWS '.$select;
		$list = $this->db
			->select($select,FALSE)
			->from($table)
			->limit($this->pagesize)
			->offset( ($this->page-1) * $this->pagesize )
			->get()
			->result_array();
		$this->list = $list;
		$count = count($list);
		// 如果$count<$pagesize 且为第一页,$count即为总条数
		if( $count < $this->pagesize && $this->page==1 ){
			$this->rowCount = $count;
		}else{
			$this->rowCount  = $this->db->query('SELECT FOUND_ROWS() AS total ')->row()->total;
		}
		
		
		if( isset($_REQUEST['format']) && $_REQUEST['format']=='json' ){
			$out = array();
			$out['count'] = $this->rowCount;
			$out['list']  = $list;
			echo json_encode($out);
			exit();
		}
		return $list;
	}
	
	public function pageData($current,$count,$pagesize=20,$size=10,$cfg=array()){
		// 每页URL路径
		$path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
		$get = empty($cfg['get']) ? $_GET : $cfg['get'];
		unset($get['page']);
		$url = $path.'?';
		foreach($get as $k=>$v){
			$url.=$k.'='.$v.'&';
		}
		$url.='page=';
		//总页数
		$pagecount = ceil($count/$pagesize);
		// 		$size = ceil($size/2);
		// 显示的最小页码数
		$min = $current-floor($size/2);
		$min = $min > 1 ? $min : 1;
		// 显示的最大页码数
		$max = $min+$size-1;
		$max = $max >= $pagecount ? $pagecount : $max;
		
// 		$list = array();
// 		if( $current>1 ){
// 			$list[0] = array('text'=>'首页','href'=>$url.'1');
// 			$list[1] = array('text'=>'上一页','href'=>$url.($current-1));
// 		}
// 		for($i=$min;$i<=$max;$i++){
// 			$list[] = array(
// 					'text'=>$i,
// 					'href'=>$url.$i,
// 			);
// 		}
// 		if( $current<$pagecount ){
// 			$list[] = array('text'=>'下一页','href'=>$url.($current+1));
// 			$list[] = array('text'=>'未页','href'=>$url.$pagecount);
// 		}
		
		return array(
				'rowCount'=>$count,
				'current'=>$current,
				'max'=>$max,
				'min'=>$min,
				'pageCount'=>$pagecount,
				'urlPrefix'=>$url,
		);
		
	}
	
	/**
	 * 分页
	 * @param int $current		当前页码
	 * @param int $count		数据条数
	 * @param int $pagesize		每页条数
	 * @param int $size 		显示页码个数
	 * @param array $cfg		其他配置参数
	 */
	public function page($current,$count,$pagesize=20,$size=10,$cfg=array()){
		// 每页URL路径
		$path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
		$get = empty($cfg['get']) ? $_GET : $cfg['get'];
		unset($get['page']);
		$url = $path.'?';
		foreach($get as $k=>$v){
			$url.=$k.'='.$v.'&';
		}
		$url.='page=';
		
		$str = '';
		//总页数
		$pagecount = ceil($count/$pagesize);
// 		$size = ceil($size/2);
		// 显示的最小页码数
		$min = $current-floor($size/2);
		$min = $min > 1 ? $min : 1;
		// 显示的最大页码数
		$max = $min+$size-1;
		$max = $max >= $pagecount ? $pagecount : $max;
		if( $current>1 ){
			$str.= '<a href="'.$url.'1'.'">'.'首页'.'</a>';
			// 挂载上一页附加数据
			$str.= '<a href="'.$url.($current-1).'">'.'上一页'.'</a>';
		}
		
		for($i=$min;$i<=$max;$i++){
			if($i==$current){
				$str.='<a><b>'.$i.'/'.$pagecount.'</b></a>';
			}else{
				$str.='<a href="'.$url.$i.'">'.$i.'</a>';
			}
		}
		if( $current<$pagecount ){
			// 挂载下一页附加数据
			$str.= '<a href="'.$url.($current+1).'">'.'下一页'.'</a>';
			$str.= '<a href="'.$url.$pagecount.'">'.'未页'.'</a>';
		}
		return $str;
	}
	
	public function setPagins($current,$totalRows,$pagesize){
		$this->page = $current;
		$this->rowCount = $totalRows;
		$this->pagesize = $pagesize;
	}

	public function show($temp=array(),$callback=NULL){
		$temp['tpl'] = $this;
		if( !isset($temp['tdList']) ){
			if( NULL !==$callback ){
				$temp['tdList'] = array_map($callback, $this->list);
			}
		}
		if( isset($temp['tableTitle']) ){
			$temp['tableTitle'] = sprintf($temp['tableTitle'],$this->rowCount);
		}else{
			$temp['tableTitle'] = '数据列表';
		}
		
		$temp['_pageData']   = $this->pageData($this->page,$this->rowCount, $this->pagesize);
		
		if( $this->debug ){
			$this->ci->output->enable_profiler(TRUE);
		}
		$this->ci->load->view($this->tplPath,$temp);
	}
	
	public function showTpl($temp = array()){
		$tplPath = 'search_tpl_ng.php';
		$temp['tpl'] = $this;

		if( isset($temp['tableTitle']) ){
			$temp['tableTitle'] = sprintf($temp['tableTitle'],$this->rowCount);
		}else{
			$temp['tableTitle'] = '数据列表';
		}
		
		$temp['_pageData']   = $this->pageData($this->page,$this->rowCount, $this->pagesize);
		
		if( $this->debug ){
			$this->ci->output->enable_profiler(TRUE);
		}
		$this->ci->load->view($tplPath,$temp);
	}
	
	
	
	
	
	
	public function createFormItem($cfg){
		$tag = isset($cfg['tag']) ? $cfg['tag'] : 'input';
		$label = isset($cfg['label']) ? $cfg['label'] : '&nbsp;';
		$label = '<label>'.$label.'</label>';
		
		return $label.$this->$tag($cfg);
	}
	
	
	/**
	 * 创建一个HTML button标签
	 * 	可以将所有参数以数组形式作为第一个参数传入,数组键名为:text,class,type,id
	 * @param string|array $text 
	 * @param string $class
	 * @param string $type
	 * @param string $id
	 * @return string
	 */
	static function button($text,$class='ibtn',$type='button',$id=''){
		if( is_array($text) ){
			foreach ($text as $k=>$v){
				switch ($k) {
					case 'id':
						$id = 'id="'.$v.'"';
						break;
					case 'class':
					case 'type':
					case 'text':
						$$k = $v;
						break;
				}
			}
		}else{
			if( !empty($id) ){
				$id = 'id="'.$id.'"';
			}
		}
		
		
		return sprintf('<button %s type="%s" class="%s">%s</button>',$id,$type,$class,$text);
		
		
// 		$class = isset($cfg['class']) ? $cfg['class'] : 'ibtn';
// 		$text  = isset($cfg['text']) ? $cfg['text'] : '';
// 		$id    = isset($cfg['id'])   ? 'id="'.$cfg['id'].'"' : '';
// 		$type  = isset($cfg['type']) ? $cfg['type']
		
// 		$html = '<button class="'.$class.'" '.$id.' ';
// 		if (!empty($cfg['on'])){
// 			foreach ($cfg['on'] as $event=>$callback){
// 				$html.=' on'.$event.'="'.$callback.'" ';
// 			}
// 		}
// 		$html.='>'.$text.'</button>';
// 		return $html;
	}
	
	static function label($cfg){
		return  '<label>'.$cfg['label'].'</label>';
	}
	
	static function input($cfg){
		$id    = isset($cfg['id'])   ? 'id="'.$cfg['id'].'"' : '';
		$type  = isset($cfg['type'])   ? $cfg['type'] : 'text';
		$class = isset($cfg['class']) ? $cfg['class'] : 'scinput1';
		$value = isset($cfg['value'])   ? $cfg['value'] : '';
		$name  = isset($cfg['name']) ? $cfg['name'] : '';
		
		return sprintf('<input %s  name="%s" type="%s" class="%s" value="%s" />',$id,$name,$type,$class,$value);
	}
	
}

// bak
// public function searchForm($form,$def=''){
// 	$input['uid'] = '<label>用户ID</label><input type="text" class="scinput1" name="uid" />';
// 	$input['nickname'] = '<label>用户昵称</label><input type="text" class="scinput1" name="nickname" />';
// 	$input['st'] = '<label>起始时间</label><input type="text" class="scinput1" name="st" />';
// 	$input['et'] = '<label>截至时间</label><input type="text" class="scinput1" name="et" />';
// 	$input['uid'] = '<label>用户ID</label><input type="text" class="scinput1" name="uid" />';
// 	$this->temp['form'] = $form;
// }

// public function header($header){
// 	$this->temp['header'] = $header;
// }

// public function title($title){
// 	$this->temp['title'] = $title;
// }

// public function dateList($list){
// 	$this->temp['list'] = $list;
// }


